const CacheManager = require('cache-manager');
const redisStore = require('cache-manager-ioredis');
const cacheConfig = require('../../../config/sys.json');
const { getRedisClient } = require('../database/redis');

let cacheManager = null;

async function getCacheManager () {
    if (!cacheManager) {
        const enableRedis = cacheConfig.isEnableRedis;
        if (enableRedis) {
            cacheManager = CacheManager.caching({
                store: redisStore,
                redisInstance: await getRedisClient()
            });
        } else {
            cacheManager = CacheManager.caching({ store: 'memory', max: 1000 });
        }
    }
    return cacheManager;
}

/**
 * 写缓存
 * @param cacheKey    缓存键
 * @param cacheData   缓存数据
 * @param ttl         缓存时间单位:s
 * @returns {Promise<*>}
 */
async function writeCache (cacheKey, cacheData, ttl) {
    const cacheManager = await getCacheManager();
    return cacheManager.set(cacheKey, cacheData, { ttl: ttl });
}

/**
 * 读缓存
 * @param cacheKey
 * @returns {Promise<*>}
 */
async function readCache (cacheKey) {
    const cacheManager = await getCacheManager();
    return cacheManager.get(cacheKey);
}

/**
 * 移除缓存
 * @param cacheKey
 * @returns {Promise<*>}
 */
async function removeCache (cacheKey) {
    const cacheManager = await getCacheManager();
    return cacheManager.del(cacheKey);
}

/**
 * 判断是否存在缓存
 * @param cacheKey
 * @returns {Promise<boolean>}
 */
async function existCache (cacheKey) {
    const cacheData = await readCache(cacheKey);
    return cacheData != null;
}

module.exports = {
    writeCache,
    readCache,
    removeCache,
    existCache
};
